package com.my.vertx.tcp;

import io.vertx.core.Vertx;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetServerOptions;

/**
 * 使用vertx创建TCP服务
 * <p>
 * <a href="https://vertx.io/docs/vertx-core/java/#_creating_a_tcp_server">Creating a TCP server</a>
 * </p>
 *
 * @author: marshal
 * @date: 2023-04-17 11:40
 */
public class VertxTcpServerTest {
    public static void main(String[] args) {
        Vertx vertx = Vertx.vertx();
        // TCP Server 配置
        NetServerOptions options = new NetServerOptions()
                .setPort(9800)
                .setLogActivity(true)
                .setHost("127.0.0.1");

        // 创建TCP Server
        NetServer server = vertx.createNetServer(options);

        // 处理响应
        server.connectHandler(socket -> {
            // socket 处理
            socket.handler(buffer -> {
                System.out.println("receive data from client : " + buffer);
            });
            //  socket 写入数据
            socket.write("This is server!", "UTF-8");

            // socket关闭处理
            socket.closeHandler(v -> {
                System.out.println("The socket has been closed");
            });
        });

        // 开始监听
        server
                .listen()
                .onComplete(res -> {
                    if (res.succeeded()) {
                        System.out.println("Server is now listening on actual port: " + server.actualPort());
                    } else {
                        System.out.println("Failed to bind!");
                    }
                });
    }
}
